<div class="sso standardContainer">
    <div class="ui basic segment">
        <h2>SSO</h2>
        <p>Single Sign-On (SSO) and authentication providers settings </p>
    </div>
    <div class="ui divider"></div>
    <div class="ui top attached tabular menu ssoTabs">
        <a class="item active" data-tab="forward_auth_tab">Forward Auth</a>
        <a class="item" data-tab="oauth2_tab">OAuth 2.0</a>
        <!-- <a class="item" data-tab="zoraxy_sso_tab">Zoraxy SSO</a> -->
        </div>
        <div class="ui bottom attached tab segment active" data-tab="forward_auth_tab">
        <!-- Forward Auth -->
        <h2>Forward Auth</h2>
        <p>Configuration settings for the Forward Auth provider.</p>
        <p>The Forward Auth provider makes a subrequest to an authorization server that supports Forward Auth, then either:</p>
        <ul>
            <li>Allows the request to flow through to the backend when the authorization server responds with a 200-299 status code.</li>
            <li>Responds with the response from the authorization server.</li>
        </ul>
        <p>Example authorization servers that support this:</p>
        <ul>
            <li><a href="https://www.authelia.com" rel=”noopener noreferrer” target="_blank">Authelia</a></li>
            <li><a href="https://goauthentik.io/" rel=”noopener noreferrer” target="_blank">Authentik</a></li>
            <li><a href="https://oauth2-proxy.github.io/oauth2-proxy/" rel=”noopener noreferrer” target="_blank">OAuth2 Proxy</a></li>
        </ul>
        <form class="ui form" action="#" id="forwardAuthSettings">
            <div class="field">
                <label for="forwardAuthAddress">Address</label>
                <input type="text" id="forwardAuthAddress" name="forwardAuthAddress" placeholder="Enter Forward Auth Address">
                <small>The full remote address or URL of the authorization servers forward auth endpoint. <strong>Example:</strong> http://127.0.0.1:9091/authz/forward-auth</small>
            </div>
            <div class="ui basic segment advanceoptions" style="margin-top:0.6em;">
                <div class="ui advancedSSOForwardAuthOptions accordion">
                    <div class="title">
                        <i class="dropdown icon"></i>
                        Advanced Options
                    </div>
                    <div class="content">
                        <div class="field">
                            <label for="forwardAuthResponseHeaders">Response Headers</label>
                            <input type="text" id="forwardAuthResponseHeaders" name="forwardAuthResponseHeaders" placeholder="Enter Forward Auth Response Headers">
                            <small>
                                Comma separated list of case-insensitive headers to copy from the authorization servers response to the request sent to the backend. If not set no headers are copied. <br>
                                <strong>Example:</strong> <code>Remote-User,Remote-Groups,Remote-Email,Remote-Name</code>
                            </small>
                        </div>
                        <div class="field">
                            <label for="forwardAuthResponseClientHeaders">Response Client Headers</label>
                            <input type="text" id="forwardAuthResponseClientHeaders" name="forwardAuthResponseClientHeaders" placeholder="Enter Forward Auth Response Client Headers">
                            <small>
                                Comma separated list of case-insensitive headers to copy from the authorization servers response to the <b><i>response sent to the client</i></b>. If not set no headers are copied. <br>
                                <strong>Example:</strong> <code>Set-Cookie,WWW-Authenticate</code>
                            </small>
                        </div>
                        <div class="field">
                            <label for="forwardAuthRequestHeaders">Request Headers</label>
                            <input type="text" id="forwardAuthRequestHeaders" name="forwardAuthRequestHeaders" placeholder="Enter Forward Auth Request Headers">
                            <small>
                                Comma separated list of case-insensitive headers to copy from the original request to the <b><i>request made to the authorization server</i></b>. If not set all headers are copied. <br>
                                <strong>Recommendation:</strong> Generally it's recommended to leave this blank or use the below example for predictable results. <br>
                                <strong>Example:</strong> <code>Accept,X-Requested-With,Cookie,Authorization,Proxy-Authorization</code>
                            </small>
                        </div>
                        <div class="field">
                            <label for="forwardAuthRequestIncludedCookies">Request Included Cookies</label>
                            <input type="text" id="forwardAuthRequestIncludedCookies" name="forwardAuthRequestIncludedCookies" placeholder="Enter Forward Auth Request Included Cookies">
                            <small>
                                Comma separated list of case-sensitive cookie names to copy from the original request to the <b><i>request made to the authorization server</i></b>. If not set all cookies are included. This allows omitting all cookies not required by the authorization server.<br>
                                <strong>Example:</strong> <code>authelia_session,another_session</code>
                            </small>
                        </div>
                        <div class="field">
                            <label for="forwardAuthRequestExcludedCookies">Request Excluded Cookies</label>
                            <input type="text" id="forwardAuthRequestExcludedCookies" name="forwardAuthRequestExcludedCookies" placeholder="Enter Forward Auth Request Excluded Cookies">
                            <small>
                                Comma separated list of case-sensitive cookie names to exclude from the <b><i>request made to the backend application</i></b>. If not set no cookies are excluded. This allows omitting the cookie intended only for the authorization server.<br>
                                <strong>Example:</strong> <code>authelia_session,another_session</code>
                            </small>
                        </div>
                        <div class="ui checkbox">
                            <input type="checkbox" id="forwardAuthRequestIncludeBody" name="forwardAuthRequestIncludeBody" value="Forward Auth Request Include Request Body">
                            <label for="forwardAuthRequestIncludeBody">Forward Auth Request Include Request Body<br><small>This allows the request body from the <b><i>request made from the client</i></b> to be included in the <b><i>request made to the authorization server</i></b>. Generally this should not be enabled.</small></label>
                        </div>
                        <div class="ui checkbox">
                            <input type="checkbox" id="forwardAuthRequestUseXOriginalHeaders" name="forwardAuthRequestUseXOriginalHeaders" value="Use X-Original-* Headers">
                            <label for="forwardAuthRequestUseXOriginalHeaders">Use X-Original-* Headers<br><small>This is used for implementations which do not use the X-Forwarded-* headers. In addition if the authorization server responds with a 401 and Location header the status will be changed to 302.</small></label>
                        </div>
                    </div>
                </div>
            </div>
            <button class="ui basic button" type="submit"><i class="green check icon"></i> Apply Change</button>
            <button class="ui basic button" type="button" id="forwardAuthClear"><i class="red trash icon"></i> Clear</button>
        </form>
        </div>
        <div class="ui bottom attached tab segment" data-tab="oauth2_tab">
        <!-- OAuth 2.0 -->
        <h2>OAuth 2.0</h2>
        <p>Configuration settings for OAuth 2.0 authentication provider.</p>

        <form class="ui form" action="#" id="oauth2Settings">
            <div class="field">
                <label for="oauth2ClientId">Client ID</label>
                <input type="text" id="oauth2ClientId" name="oauth2ClientId" placeholder="Enter Client ID">
                <small>Public identifier of the OAuth2 application</small>
            </div>
            <div class="field">
                <label for="oauth2ClientSecret">Client Secret</label>
                <input type="password" id="oauth2ClientSecret" name="oauth2ClientSecret" placeholder="Enter Client Secret">
                <small>Secret key of the OAuth2 application</small>
            </div>
            <div class="field">
                <label for="oauth2CodeChallengeMethod">Code Challenge Method</label>

                <div class="ui selection dropdown" id="oauth2CodeChallengeMethod">
                    <input type="hidden" name="oauth2CodeChallengeMethod">
                    <i class="dropdown icon"></i>
                    <div class="default text">Plain</div>
                    <div class="menu">
                        <div class="item" data-value="plain">Plain</div>
                        <div class="item" data-value="PKCE">PKCE</div>
                        <div class="item" data-value="PKCE_S256">PKCE (S256)</div>
                    </div>
                </div>
                <small>Options: <br>
                    Plain: No code challenge is used.<br>
                    PKCE: Uses a code challenge for added security.<br>
                    PKCE (S256): Uses a hashed code challenge (SHA-256) for maximum protection.<br>
                    <strong>Note:</strong> PKCE (especially S256) is recommended for better security.
                </small>
            </div>
            <div class="field">
                <label for="oauth2WellKnownUrl">Discovery URL</label>
                <input type="text" id="oauth2WellKnownUrl" name="oauth2WellKnownUrl" placeholder="Enter Well-Known URL">
                <small>URL to the OpenID Connect 1.0 Discovery document (usually ending with /.well-known/openid-configuration). Used to automatically fetch provider settings.</small>
            </div>

            <div class="field">
                <label for="oauth2ServerUrl">Authorization URL</label>
                <input type="text" id="oauth2ServerUrl" name="oauth2ServerUrl" placeholder="Enter Authorization URL">
                <small>URL used to authenticate against the OAuth2 provider. Will redirect the user to the OAuth2 provider login view. Optional if Well-Known url is configured.</small>
            </div>

            <div class="field">
                <label for="oauth2TokenUrl">Token URL</label>
                <input type="text" id="oauth2TokenUrl" name="oauth2TokenUrl" placeholder="Enter Token URL">
                <small>URL used by Zoraxy to exchange a valid OAuth2 authentication code for an access token. Optional if Well-Known url is configured.</small>
            </div>

            <div class="field">
                <label for="oauth2UserInfoURL">User Info URL</label>
                <input type="text" id="oauth2UserInfoURL" name="oauth2UserInfoURL" placeholder="Enter User Info URL">
                <small>URL used by the OAuth2 provider to validate generated token. Optional if Well-Known url is configured.</small>
            </div>

            <div class="field">
                <label for="oauth2Scopes">Scopes</label>
                <input type="text" id="oauth2Scopes" name="oauth2Scopes" placeholder="Enter Scopes">
                <small>Scopes required by the OAuth2 provider to retrieve information about the authenticated user. Refer to your OAuth2 provider documentation for more information about this. Optional if Well-Known url is configured.</small>
            </div>

            <div class="field">
                <label for="oauth2ConfigurationCacheTime">Configuration cache time</label>
                <input type="text" id="oauth2ConfigurationCacheTime" name="oauth2ConfigurationCacheTime" placeholder="Enter Configuration Cache Time">
                <small>Time to cache OAuth2 configuration before refresh. Accepts Go time.Duration format (e.g. 1m, 10m, 1h). Defaults to 60s.</small>
            </div>

            <button class="ui basic button" type="submit"><i class="green check icon"></i> Apply Change</button>
            <button class="ui basic button" type="button" id="oauth2Clear"><i class="red trash icon"></i> Clear</button>
        </form>
        </div>
        <div class="ui bottom attached tab segment" data-tab="zoraxy_sso_tab">
            <!-- Zoraxy SSO -->
            <h3>Zoraxy SSO</h3>
            <p>Configuration settings for Zoraxy SSO provider.</p>
            <p>Currently not implemented.</p>
        </div>
</div>

<script>
    $(".ssoTabs .item").tab();

    $(document).ready(function() {
        /* Load Forward Authz settings from backend */
        getForwardAuthSettings();

        /* Load OAuth 2.0 settings from backend */
        getOAuth20Settings();

        /* Add more initialization code here if needed */
    });

    /*
        Forward Auth settings fetcher.
    */
    function getForwardAuthSettings() {
        $.cjax({
            url: '/api/sso/forward-auth',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                $('#forwardAuthAddress').val(data.address);
                if (data.responseHeaders != null) {
                    $('#forwardAuthResponseHeaders').val(data.responseHeaders.join(","));
                } else {
                    $('#forwardAuthResponseHeaders').val("");
                }
                if (data.responseClientHeaders != null) {
                    $('#forwardAuthResponseClientHeaders').val(data.responseClientHeaders.join(","));
                } else {
                    $('#forwardAuthResponseClientHeaders').val("");
                }
                if (data.requestHeaders != null) {
                    $('#forwardAuthRequestHeaders').val(data.requestHeaders.join(","));
                } else {
                    $('#forwardAuthRequestHeaders').val("");
                }
                if (data.requestIncludedCookies != null) {
                    $('#forwardAuthRequestIncludedCookies').val(data.requestIncludedCookies.join(","));
                } else {
                    $('#forwardAuthRequestIncludedCookies').val("");
                }
                if (data.requestExcludedCookies != null) {
                    $('#forwardAuthRequestExcludedCookies').val(data.requestExcludedCookies.join(","));
                } else {
                    $('#forwardAuthRequestExcludedCookies').val("");
                }
                if (data.requestIncludeBody != null && data.requestIncludeBody === true) {
                    $("#forwardAuthRequestIncludeBody").parent().checkbox("set checked");
                } else {
                    $("#forwardAuthRequestIncludeBody").parent().checkbox("set unchecked");
                }
                if (data.useXOriginalHeaders != null && data.useXOriginalHeaders === true) {
                    $("#forwardAuthRequestUseXOriginalHeaders").parent().checkbox("set checked");
                } else {
                    $("#forwardAuthRequestUseXOriginalHeaders").parent().checkbox("set unchecked");
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error fetching SSO settings:', textStatus, errorThrown);
            }
        });
    }

    /*
        Forward Auth settings update handler.
    */
    $("#forwardAuthSettings").on("submit", function(event) {
        event.preventDefault();

        const address = $('#forwardAuthAddress').val();
        const responseHeaders = $('#forwardAuthResponseHeaders').val();
        const responseClientHeaders = $('#forwardAuthResponseClientHeaders').val();
        const requestHeaders = $('#forwardAuthRequestHeaders').val();
        const requestIncludedCookies = $('#forwardAuthRequestIncludedCookies').val();
        const requestExcludedCookies = $('#forwardAuthRequestExcludedCookies').val();
        const requestIncludeBody = $('#forwardAuthRequestIncludeBody').is(':checked');
        const useXOriginalHeaders = $('#forwardAuthRequestUseXOriginalHeaders').is(':checked');

        console.log(`Updating Forward Auth settings. Address: ${address}. Response Headers: ${responseHeaders}. Response Client Headers: ${responseClientHeaders}. Request Headers: ${requestHeaders}. Request Included Cookies: ${requestIncludedCookies}. Request Excluded Cookies: ${requestExcludedCookies}. Request Include Body: ${requestIncludeBody}. Use X-Original-* Headers: ${useXOriginalHeaders}.`);

        $.cjax({
            url: '/api/sso/forward-auth',
            method: 'POST',
            data: {
                address: address,
                responseHeaders: responseHeaders,
                responseClientHeaders: responseClientHeaders,
                requestHeaders: requestHeaders,
                requestIncludedCookies: requestIncludedCookies,
                requestExcludedCookies: requestExcludedCookies,
                requestIncludeBody: requestIncludeBody,
                useXOriginalHeaders: useXOriginalHeaders,
            },
            success: function(data) {
                if (data.error !== undefined) {
                    msgbox(data.error, false);
                    return;
                }
                msgbox('Forward Auth settings updated', true);
                console.log('Forward Auth settings updated:', data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error updating Forward Auth settings:', textStatus, errorThrown);
            }
        });
    });

    $( "#forwardAuthClear" ).on( "click", function( event ) {
        event.preventDefault();

        $.cjax({
            url: '/api/sso/forward-auth',
            method: 'DELETE',
            success: function(data) {
                if (data.error != undefined) {
                    msgbox(data.error, false);
                    return;
                }

                getForwardAuthSettings();

                msgbox('Forward Auth settings cleared', true);
                console.log('Forward Auth settings cleared:', data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error clearing Forward Auth settings:', textStatus, errorThrown);
                msgbox('Error clearing Forward Auth settings, check console', false);
            }
        });
    });

    /*
        OAuth 2.0 settings fetcher.
    */
    function getOAuth20Settings() {
        $.cjax({
            url: '/api/sso/OAuth2',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                $('#oauth2WellKnownUrl').val(data.oauth2WellKnownUrl);
                $('#oauth2ServerUrl').val(data.oauth2ServerUrl);
                $('#oauth2TokenUrl').val(data.oauth2TokenUrl);
                $('#oauth2UserInfoUrl').val(data.oauth2UserInfoUrl);
                $('#oauth2ClientId').val(data.oauth2ClientId);
                $('#oauth2ClientSecret').val(data.oauth2ClientSecret);
                $('#oauth2Scopes').val(data.oauth2Scopes);
                $('#oauth2ConfigurationCacheTime').val(data.oauth2ConfigurationCacheTime);
                $('[data-value="'+data.oauth2CodeChallengeMethod+'"]').click();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error fetching SSO settings:', textStatus, errorThrown);
            }
        });
    }

    /*
        OAuth 2.0 settings update handler.
    */
    $( "#oauth2Settings" ).on( "submit", function( event ) {
        event.preventDefault();

        if ($('#oauth2ClientId').val().length === 0 || $('#oauth2ClientSecret').val().length === 0) {
            msgbox("You must specify the Client ID and Client Secret.", false);

            return;
        }

        if ($('#oauth2WellKnownUrl').val().length === 0) {
            if ($('#oauth2ServerUrl').val().length === 0 || $('#oauth2TokenUrl').val().length === 0 || $('#oauth2UserInfoURL').val().length === 0 || $('#oauth2Scopes').val().length === 0) {
                msgbox("You must specify either the Well Known URL or configure the Authorization URL, Token URL, User Info URL, and Scopes.", false);

                return;
            }
        }

        $.cjax({
            url: '/api/sso/OAuth2',
            method: 'POST',
            data: $( this ).serialize(),
            success: function(data) {
                if (data.error != undefined) {
                    msgbox(data.error, false);
                    return;
                }
                msgbox('OAuth2 settings updated', true);
                console.log('OAuth2 settings updated:', data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error updating OAuth2 settings:', textStatus, errorThrown);
                msgbox('Error updating OAuth2 settings, check console', false);
            }
        });
    });

    $( "#oauth2Clear" ).on( "click", function( event ) {
        event.preventDefault();

        $.cjax({
            url: '/api/sso/OAuth2',
            method: 'DELETE',
            success: function(data) {
                if (data.error != undefined) {
                    msgbox(data.error, false);
                    return;
                }

                getOAuth20Settings();

                msgbox('OAuth2 settings cleared', true);
                console.log('OAuth2 settings cleared:', data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error clearing OAuth2 settings:', textStatus, errorThrown);
                msgbox('Error clearing OAuth2 settings, check console', false);
            }
        });
    });

    /* Bind UI events */
    $(".sso .advanceSettings").accordion();
</script>